<?php

/**
 * Mandatory public API of emedia module
 *
 * @copyright (c) 2012 University of Geneva
 * @license GNU General Public License - http://www.gnu.org/copyleft/gpl.html
 * @author Laurent Opprecht laurent@opprecht.info
 */
defined('MOODLE_INTERNAL') || die;

require_once($CFG->dirroot . '/mod/emedia/lib/emedia.class.php');
require_once($CFG->dirroot . '/mod/emedia/lib/emedia_store.class.php');

/**
 * List of features supported in emedia module
 * @param string $feature FEATURE_xx constant for requested feature
 * @return mixed True if module supports feature, false if not, null if doesn't know
 */
function emedia_supports($feature)
{
    switch ($feature)
    {
        case FEATURE_MOD_ARCHETYPE: return MOD_ARCHETYPE_RESOURCE;
        case FEATURE_GROUPS: return false;
        case FEATURE_GROUPINGS: return false;
        case FEATURE_GROUPMEMBERSONLY: return true;
        case FEATURE_MOD_INTRO: return true;
        case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
        case FEATURE_GRADE_HAS_GRADE: return false;
        case FEATURE_GRADE_OUTCOMES: return false;
        case FEATURE_BACKUP_MOODLE2: return true;
        case FEATURE_SHOW_DESCRIPTION: return true;

        default: return null;
    }
}

/**
 * Returns all other caps used in module
 * @return array
 */
function emedia_get_extra_capabilities()
{
    return array('moodle/site:accessallgroups');
}

/**
 * This function is used by the reset_course_userdata function in moodlelib.
 * @param $data the data submitted from the reset course.
 * @return array status array
 */
function emedia_reset_userdata($data)
{
    return array();
}

/**
 * List of view style log actions
 * @return array
 */
function emedia_get_view_actions()
{
    return array('view', 'view all');
}

/**
 * List of update style log actions
 * @return array
 */
function emedia_get_post_actions()
{
    return array('update', 'add');
}

/**
 * Add emedia instance.
 * 
 * @param object $data
 * @param object $mform
 * @return int new emedia instance id
 */
function emedia_add_instance($data, $mform)
{
    global $CFG, $DB;

    $options = array();
    $options['size'] = $data->size;

    $data->options = serialize($options);
    $data->url = EMedia::filter_url($data->url);

    require_once($CFG->dirroot . '/mod/emedia/renderer/asset_renderer.class.php');
    $info = AssetRenderer::get($data->url, $options);
    $data->data = serialize($info);
    $data->snippet = $info[AssetRenderer::EMBED_SNIPPET];

    $data->ctime = time();
    $data->mtime = time();
    $data->id = $DB->insert_record('emedia', $data);

    return $data->id;
}

/**
 * Update emedia instance.
 * 
 * @param object $data
 * @param object $mform
 * @return bool true
 */
function emedia_update_instance($data, $mform)
{
    global $CFG, $DB;

    $options = array();
    $options['size'] = $data->size;

    $data->options = serialize($options);
    $data->url = EMedia::filter_url($data->url);

    require_once($CFG->dirroot . '/mod/emedia/renderer/asset_renderer.class.php');
    $info = AssetRenderer::get($data->url, $options);
    $data->data = serialize($info);
    $data->snippet = $info[AssetRenderer::EMBED_SNIPPET];

    $data->mtime = time();
    $data->id = $data->instance;

    $DB->update_record('emedia', $data);
    return true;
}

/**
 * Delete emedia instance.
 * 
 * @param int $id
 * @return bool true
 */
function emedia_delete_instance($id)
{
    global $DB;

    if (!$mod = $DB->get_record('emedia', array('id' => $id)))
    {
        return false;
    }

    $DB->delete_records('emedia', array('id' => $mod->id));

    return true;
}

/**
 * Return use outline
 * 
 * @param object $course
 * @param object $user
 * @param object $mod
 * @param object $url
 * @return object|null
 */
function emedia_user_outline($course, $user, $mod, $url)
{
    global $DB;

    if ($logs = $DB->get_records('log', array('userid' => $user->id, 'module' => 'emedia',
        'action' => 'view', 'info' => $url->id), 'time ASC'))
    {

        $numviews = count($logs);
        $lastlog = array_pop($logs);

        $result = new stdClass();
        $result->info = get_string('numviews', '', $numviews);
        $result->time = $lastlog->time;

        return $result;
    }
    return null;
}

/**
 * Return use complete
 * 
 * @param object $course
 * @param object $user
 * @param object $mod
 * @param object $url
 */
function emedia_user_complete($course, $user, $mod, $url)
{
    global $CFG, $DB;

    if ($logs = $DB->get_records('log', array('userid' => $user->id, 'module' => 'emedia',
        'action' => 'view', 'info' => $url->id), 'time ASC'))
    {
        $numviews = count($logs);
        $lastlog = array_pop($logs);

        $strmostrecently = get_string('mostrecently');
        $strnumviews = get_string('numviews', '', $numviews);

        echo "$strnumviews - $strmostrecently " . userdate($lastlog->time);
    }
    else
    {
        print_string('neverseen', 'emedia');
    }
}

/**
 * Returns the users with data in one emedia
 *
 * @todo: deprecated - to be deleted in 2.2
 *
 * @param int $id
 * @return bool false
 */
function emedia_get_participants($id)
{
    return false;
}

/**
 * Given a course_module object, this function returns any
 * "extra" information that may be needed when printing
 * this activity in a course listing.
 *
 * See {@link get_array_of_activities()} in course/lib.php
 *
 * @param object $coursemodule
 * @return object info
 */
function emedia_get_coursemodule_info($coursemodule)
{
    global $DB, $CFG;
    require_once($CFG->dirroot . '/mod/emedia/renderer/asset_renderer.class.php');

    $emedia = EMediaStore::select_by_cm($coursemodule);
    if (empty($emedia))
    {
        return null;
    }

    $info = new cached_cm_info();

    $data = $emedia->data;

    //name
    $name = trim($emedia->name);
    $name = $name ? $name : $data[AssetRenderer::TITLE];
    $name = $name ? $name : $data->url;
    $info->name = $name;

    //icon
    $info->iconurl = isset($data[AssetRenderer::ICON]) ? $data[AssetRenderer::ICON] : null;

    if ($coursemodule->showdescription)
    {
        $content = '';
        if ($emedia->intro)
        {
            $content = format_module_intro('emedia', $emedia, $coursemodule->id, false);
        }
        else
        {
            $content = $emedia->data['description'];
        }
        $content .= $emedia->snippet;
        $info->content = $content;
    }

    return $info;
}

/**
 * This function extends the global navigation for the site.
 * It is important to note that you should not rely on PAGE objects within this
 * body of code as there is no guarantee that during an AJAX request they are
 * available
 *
 * @param navigation_node $navigation The url node within the global navigation
 * @param stdClass $course The course object returned from the DB
 * @param stdClass $module The module object returned from the DB
 * @param stdClass $cm The course module instance returned from the DB
 */
function emedia_extend_navigation($navigation, $course, $module, $cm)
{
    /**
     * This is currently just a stub so that it can be easily expanded upon.
     * When expanding just remove this comment and the line below and then add
     * you content.
     */
    $navigation->nodetype = navigation_node::NODETYPE_LEAF;
}

/**
 * Return a list of page types
 * @param string $pagetype current page type
 * @param stdClass $parentcontext Block's parent context
 * @param stdClass $currentcontext Current context of block
 */
function emedia_page_type_list($pagetype, $parentcontext, $currentcontext)
{
    $module_pagetype = array('mod-emedia-*' => get_string('page-mod-emedia-x', 'emedia'));
    return $module_pagetype;
}

/**
 * Export emedia resource contents
 *
 * @return array of file content
 */
function emedia_export_contents($cm, $baseurl)
{
    global $DB;
    $contents = array();
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);

    $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
    $emedia = $DB->get_record('emedia', array('id' => $cm->instance), '*', MUST_EXIST);

    $url = str_replace('&amp;', '&', $emedia->url);
    $is_url = clean_param($url, PARAM_URL);
    if (empty($is_url))
    {
        return null;
    }

    $url = array();
    $url['type'] = 'url';
    $url['filename'] = $emedia->name;
    $url['filepath'] = null;
    $url['filesize'] = 0;
    $url['fileurl'] = $url;
    $url['timecreated'] = $emedia->ctime;
    $url['mtime'] = $emedia->mtime;
    $url['sortorder'] = null;
    $url['userid'] = null;
    $url['author'] = null;
    $url['license'] = null;
    $contents[] = $url;

    return $contents;
}
